//
//  CoreCache.swift
//  Swift-app开发基础架构
//
//  Created by pro on 2017/8/17.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

import UIKit

class KZCache: NSObject {

    // 永久保存时间
    static private let _maxExpireTime = Int32.max
    
    static func setObject(withKey key: String,
                          value: Any,
                          expireTime: Int) {
        
        let cacheValue = FastCoder.data(withRootObject: value)
        if cacheValue == nil {
            print("该数据无法解析成Data")
            return
        }
        KZDataBase.setItemWithKey(key: key,
                                    value: cacheValue!,
                                    type: String(describing: value),
                                    updateTime: Int(Date().timeIntervalSince1970),
                                    expireTime: expireTime)
    }
    static func setObject(withKey key: String,
                          value: Any) {
        
        setObject(withKey: key, value: value, expireTime: Int(_maxExpireTime))
    }
    
    static func getObject(_ key: String) -> Any? {
        
        let temp = KZDataBase.query(key: key)
        if let model = temp {
            
            let now = Date()
            let currentStamp = now.timeIntervalSince1970
            let expireTime = model.expireTime
            let updateTime = model.updateTime
            if((expireTime + updateTime) < Int(currentStamp)) { // 当前时间超过过期时间
                print("记录已过期->即将删除")
                KZDataBase.deleteItem(key: key)
                return nil;
            } else { // 未过期则取出正确的数据
                let data = model.value!
                let value = FastCoder.object(with: data)
                return value;
            }
        } else {
            print("数据库中没有该条记录")
            return nil
        }
    }
}

